// pages/userInfoCenter/index.js
const App = getApp();
const { Dialog, Toast } = require("../../../../config/modal")
const utils = require("../../../../utils/util")
const { LOGIN, LOCATION } = require("../../../../config/login.js")
Page({
    /**
     * 页面的初始数据
     */
    data: {
        notice: '各位同学请注意，所有的任务酬劳均为双方线下交易哦，任务完成后记得联系对方给予酬劳哦～',
        location_icon: '/static/img/school_location.png',
        title: "抢单中心",
        showComment: false,
        srcolltop: false,
        capsuleBarHeight: App.$getMenuButtonHeight(),
        showSonComment: false,
        isAuth: App.$isAuth(),
        userIcon: '/static/img/student.png',
        adminIcon: '/static/img/official3.png',
        offsetTop: App.globalData.window.navHeight,
        window: App.globalData.window,
        theamTextColor: App.globalData.theamTextColor,
        loadMore: {
            show: false,
            type: "loading",
            text: "加载中..."
        },
        // 用户和地址信息
        userInfo: {},
        // 文章相关数据
        mapTabValue: {
            0: [],
            1: [],
        },
        tabs: [
            {
                name: '包裹任务',
                type: "packages",
                disabled: false
            },
            {
                name: '其它任务',
                type: "otherTask",
                disabled: false
            }
        ],
        tabActiveKey: 0,
        obj: {
            0: {
                list: [],
                srcolltop: 0,
                page: {
                    pageNum: 1,
                    pageSize: 15,
                    pages: 0,
                }
            },
            1: {
                list: [],
                srcolltop: 0,
                page: {
                    pageNum: 1,
                    pageSize: 15,
                    pages: 0,
                }
            }
        },
        userConcat: {
            show: false,
        },
        page: {
            one: 1,
        },
        searchParams: {
            city: '',
            schoolName: "",
        }
        // 初始化tab,用于记录点击过后的tab,目的是让其切换来去，不进行更新数据
        , initedTab: [],

        // 我发布的
        actionFunctions1: [
            {
                image: "/static/function/package.png",
                text: "找人取快递",
                page: "myPackage",
                open: true,
            }, {
                image: "/static/function/task.png",
                text: "找人代办",
                page: "myTask",
                open: true,
            }
        ]
        //  我接受的
        , actionFunctions: [
            {
                image: "/static/function/package.png",
                text: "代取快递",
                page: "myAcceptPackage",
                open: true,
            }, {
                image: "/static/function/task.png",
                text: '帮人代办',
                page: "myAcceptTask",
                open: true,
            },

        ],
        showCenterJump: false
    },
    URL: {
        taskList: {
            0: "/packages/pageList",
            1: "/task/pageList",
        },
        checkAuth: "/customer/checkAuth",
        userConcatInfo: '/customer/userConcatInfo/?',
        task: {
            0: "/packages/toAgree/?",
            1: "/task/toAgree/?"
        }
    },
    page: {
        schoolPage: "/pages/school/index",
        userInfo: '/pages/tabbar/user/userInfoEdit/index',
        share: '/pages/tabbar/index/robOrders/share/index',
        home: '/pages/tabbar/index/index',
        target: '/pages/tabbar/index/robOrders/share/index',
        thisPage: '/pages/tabbar/index/robOrders/index',
        myPackage: "/pages/tabbar/user/userInfoCenter/myPackages/index",
        myTask: "/pages/tabbar/user/userInfoCenter/myTask/index",
        myAcceptPackage: "/pages/tabbar/user/userInfoCenter/myAcceptPackage/index",
        myAcceptTask: "/pages/tabbar/user/userInfoCenter/myAcceptTask/index",
    },
    goBack() {
        wx.navigateBack();
    },
    goHome() {
        App.$switchTab(this.page.home, false)
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        App.$handlerInviteCode(options);
        this.inInit();
        App.$on('authedCallback', this, (res) => {
            console.log("robOrders.js 接收授权成功事件消息");
            this.inInit();
        })
    },

    inInit() {
        this.initAuthInfo();
        this.setData({
            'searchParams.schoolName': this.initGetSchoolName(),
        })
        this.init(this.data.page.one, false, this.data.tabActiveKey);
    },

    onShow() {

    }
    , actionJump(e) {
        let isOpen = e.currentTarget.dataset.open;
        if (isOpen) {
            let page = e.currentTarget.dataset.page;
            this.setData({
                showCenterJump: false
            })
            App.$navigateTo(this.page[page], true);
            return;
        }
        Toast.fail('开发君，💪开发中，尽请期待!!!!')
    }
    , onShowTaskCenterPopup() {
        this.setData({
            showCenterJump: true
        })
    }
    // 关闭弹出跳转框
    , onCloseTaskCenterPopup() {
        this.setData({
            showCenterJump: false
        })
    }
    , initGetSchoolName() {
        let schoolName = App.$getData('task_schoolName');
        let userInfo = App.$getUserInfo();
        if (utils.isInvalid(schoolName)) {
            if (!utils.isInvalid(userInfo.schoolName)) {
                schoolName = userInfo.schoolName;
            }
        }
        if (!utils.isInvalid(schoolName)) {
            App.$saveData('task_schoolName', schoolName);
        }
        return schoolName;
    },


    initAuthInfo() {
        this.setData({
            'isAuth': App.$isAuth(),
            'userInfo': App.$getUserInfo(),
        })
    }
    , clearSchoolName() {
        this.setData({
            'searchParams.schoolName': '',
            'userInfo.schoolName': null,
        })
        App.$removeStore('task_schoolName');
        this.init(this.data.page.one, false, this.data.tabActiveKey);
    }
    // 选择学校后回调函数
    , onSchoolNameChange(e) {
        this.setData({
            'searchParams.schoolName': e.detail,
            'userInfo.schoolName': e.detail,
        })
        App.$saveData('task_schoolName', e.detail);
        this.init(this.data.page.one, false, this.data.tabActiveKey);
    }
    // 点击选择学校
    , reloadSchoolName() {
        App.$navigateTo(this.page.schoolPage, false)
    }
    // 初始化数据
    , init(pageNum, loadMore, tabKey) {
        let item = this.data.searchParams;

        let params = {};
        for (const itemKey in item) {
            params[itemKey] = item[itemKey];
        }
        params['pageNum'] = pageNum
        params['pageSize'] = this.data.obj[this.data.tabActiveKey].page.pageSize

        // 记录点击过的
        this.recordingClickTab(tabKey);

        // 上拉到底的时候进行显示加载中
        this.setLoadingMore(loadMore, "loading", "加载中...")

        if (!loadMore ? true : loadMore) {
            // 弹出loading
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
        }

        App.$get(!loadMore ? true : loadMore, this.URL.taskList[tabKey], params, res => {
            wx.stopPullDownRefresh();
            this.setData({
                "loadMore.show": false,
            })
            if (res.R) {
                let pageNum = 'obj.' + tabKey + '.page.pageNum'
                let pageSize = 'obj.' + tabKey + '.page.pageSize'
                let pages = 'obj.' + tabKey + '.page.pages'
                this.setData({
                    [pageNum]: res.data.pageNum,
                    [pageSize]: res.data.pageSize,
                    [pages]: res.data.pages
                })

                let newData = res.data.rows;
                let sourceData = this.data.obj[tabKey].list;
                let listKey = 'obj.' + tabKey + '.list';
                if (!loadMore) {
                    sourceData = newData;
                } else {
                    // 上啦刷新，列表追加数据
                    newData.forEach(data => {
                        sourceData.push(data);
                    })
                }
                let mapTabValue = 'mapTabValue[' + tabKey + ']';
                this.setData({
                    [listKey]: sourceData,
                    [mapTabValue]: sourceData,
                })
            }

            if (!loadMore ? true : loadMore) {
                wx.hideLoading();
            }
        })
    },

    // tab栏切换
    onTypeChange(event) {
        let index = event.detail.index;
        this.setData({
            'tabActiveKey': index,
        })
        this.setLoadingMore(false, "", "");

        // 没点击过的tab
        if (this.data.initedTab.indexOf(index) < 0) {
            let pageNum = 'obj.' + index + '.page.pageNum'
            // 第一页开始
            this.setData({
                [pageNum]: this.data.page.one,
            })
            this.init(this.data.page.one, false, index)
        }
        this.setScrollTop(this.data.obj[index].srcolltop)
    }

    // 记录点击过的tab栏 再次点击的时候，不让他刷新
    , recordingClickTab(index) {
        if (this.data.initedTab.indexOf(index) < 0) {
            let tabKeyed = this.data.initedTab;
            tabKeyed.push(index);
            this.setData({
                'initedTab': tabKeyed
            })
        }
    }

    , getUserConcat(e) {
        let userCode = e.currentTarget.dataset.usercode
        let userConcat = this.data.userConcat[userCode];
        if (utils.isInvalid(userConcat)) {
            App.$get(true, this.URL.userConcatInfo.replace("?", userCode), {}, res => {
                if (res.R) {
                    let userCodeKey = "userConcat." + userCode;
                    this.setData({
                        'userConcat.item': res.data,
                        [userCodeKey]: res.data
                    })
                    this.setData({
                        'userConcat.show': true
                    })
                }
            })
            return;
        }
        this.setData({
            'userConcat.item': userConcat,
        })
        this.setData({
            'userConcat.show': true
        })
    }

    , takeOrder(e) {
        let type = e.currentTarget.dataset.type;
        let itemNo = e.currentTarget.dataset.itemno;
        let index = e.currentTarget.dataset.index;
        // 认证判断
        if (!App.$isAuth()) {
            App.$navigateToAuth();
            return;
        }

        // App.$navigateTo(this.page.target+"?taskNo="+itemNo+"&type="+(type=='packages'?0:1))
        // return;


        App.$get(true, this.URL.checkAuth, {}, res => {
            if (!res.R) {
                Dialog.alert({
                    title: '友情提示',
                    message: '完善个人信息接单率更高哦～',
                    width: "250px",
                    confirmButtonColor: "#D2691E",
                    confirmButtonText: "去完善资料",
                    showCancelButton: true,
                    cancelButtonText: "取消",
                }).then(() => {
                    App.$navigateTo(this.page.userInfo, true);
                })

                return;
            }
            let msg = "请联系对方同意接单"
            App.$post(true, this.URL.task[this.data.tabActiveKey].replace("?", itemNo), {}, res => {
                if (res.R) {

                    let data = this.data.obj[this.data.tabActiveKey].list;
                    data = data.splice(index, 1);
                    let dataKey = 'obj.' + this.data.tabActiveKey + ".list"

                    let mapTabData = this.data.mapTabValue[this.data.tabActiveKey];
                    mapTabData = mapTabData.splice(index, 1);
                    let mapTabDataKey = 'mapTabValue.' + this.data.tabActiveKey
                    this.setData({
                        [dataKey]: data,
                        [mapTabDataKey]: mapTabData
                    })

                    Dialog.alert({
                        message: msg,
                        width: "280px",
                        confirmButtonColor: "#D2691E",
                        confirmButtonText: "关闭",
                    }).then(() => {
                    });
                }
            })
        })
    }


    , closeUserInfo() {
        this.setData({
            'userConcat.show': false
        })
    }
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    , onPullDownRefresh: function () {
        this.init(1, false, this.data.tabActiveKey);
    }
    , makePhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.userphone
        })
    }
    , copyWechat(e) {
        let wechat = e.currentTarget.dataset.wechat;
        wx.setClipboardData({
            data: wechat,
            success: function (res) {
                wx.getClipboardData({
                    success: function () {
                        wx.showToast({
                            title: '已复制',
                            icon: 'none'
                        })
                    }
                })
            }
        })
    }

    /**
     * 页面上拉触底事件的处理函数
     */
    , onReachBottom: function () {
        let page = this.data.obj[this.data.tabActiveKey].page;
        if (page.pages === 0 || page.pageNum + 1 > page.pages) {
            this.setLoadingMore(true, "end", "我是有底线的~")
            return;
        }
        this.init(page.pageNum + 1, true, this.data.tabActiveKey);
    }

    , setLoadingMore(show, type, text) {
        this.setData({
            "loadMore.show": show,
            "loadMore.type": type,
            "loadMore.text": text,
        })
    }
    ,


    scrollTop() {
        this.setScrollTop(0);
    },
    setScrollTop(val) {
        wx.pageScrollTo({
            scrollTop: val,
        })
    },

    // 页面滚动出发
    onPageScroll(options) {
        let flag = false;
        if (options.scrollTop > 200) {
            flag = true;
        }
        let key = 'obj.' + this.data.tabActiveKey + '.srcolltop'
        this.setData({
            [key]: options.scrollTop
        })
        this.setData({
            srcolltop: flag
        })
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    /**
     * 用户点击右上角分享
     */
    , onShareAppMessage: function (e) {
        let item = null;
        if (e.from !== "menu") {
            item = e.target.dataset.detail
        }
        return App.$onShare(this.page.target, item, "任务分享");
    },
})
